package com.xzcs.shiro;

import com.xzcs.mapper.module.ModulePermitMapper;
import com.xzcs.util.common.StringUtils;
import org.apache.shiro.config.Ini;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * 生成权限规则，确定每个url的访问权限
 * @desc:
 * @author: chang
 * @date: 2017/6/7
 */
public class MyFilterChainDefinitionMap implements FactoryBean<Ini.Section> {
	public Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ModulePermitMapper modulePermitMapper;

	//静态资源访问权限
	private String filterChainDefinitions = null;

	/**
	 * 注：modulePermitMapper不能使用redis缓存
	 * @return
	 * @throws Exception
     */
	public Ini.Section getObject() throws Exception {
		Ini ini = new Ini();
		//加载默认的url
		ini.load(filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);

		List<Map<String, Object>> permits = modulePermitMapper.findAllPermit();
		for (Map permit : permits) {
			String permitUrl = StringUtils.get(permit, "permit_url");
			String permitCode = StringUtils.get(permit, "permit_code");
			if (!permitUrl.equals("") && !permitCode.equals("")) {
				String permission = "authc,perms[" + permitCode + "]";
				//logger.debug(permitUrl+" = "+permission);
				section.put(permitUrl, permission);
			}
		}
		// 所有资源的访问权限authc，必须放在最后
		section.put("/**", "authc");
		/*Collection<Ini.Section> s = ini.getSections();
		Iterator ss = s.iterator();
		while(ss.hasNext()){
			Ini.Section sss = (Ini.Section) ss.next();
			System.out.println("section name :"+sss.getName());
			for (Map.Entry<String, String> ddd : sss.entrySet()) {
				System.out.println(ddd.getKey()+"----"+ddd.getValue());
			}
		}*/
		return section;
	}

	/**
	 * 通过filterChainDefinitions对默认的url过滤定义
	 */
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		this.filterChainDefinitions = filterChainDefinitions;
	}

	public Class<?> getObjectType() {
		return this.getClass();
	}

	public boolean isSingleton() {
		return false;
	}
}
